﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TJBHJJ.Models;
using System.Collections;
using System.IO;
using System.Globalization;

namespace TJBHJJ.Controllers
{
    public class ManagerController : Controller
    {
        //
        // GET: /Manager/
        Home home = new Home();
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
        #region //登录
        public ActionResult LogOn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LogOn(Admin model, string returnUrl)
        {
            //这里缺少验证
            //需要写在这里
            if (home.Admins.Where(x => x.UserName == model.UserName && x.PassWord == model.PassWord).Count() >= 1)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                //FormsAuthentication.SetAuthCookie("Test", false);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Manager");
                }
            }
            else
            {
                home.Alert(Response, "登录失败，用户名或密码错误！");
                ModelState.AddModelError("LogonError", "登录失败，用户名或密码错误！");
                return RedirectToAction("Logon", "Manager");
            }
        }
        [Authorize]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Manager");
        }
        #endregion

        #region //新闻
        //新闻
        public ActionResult News()
        {
            return View(new News());
            //if (Request.IsAjaxRequest())
            //{
            //    return PartialView("News", new News());
            //}
            //else
            //{
            //    return View(new News());
            //}
        }

        [HttpPost]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult News(News news)
        {
            if (ModelState.IsValid)
            {
                news.GuidGid = Guid.NewGuid().ToString();
                news.CreatTime = DateTime.Now;
                news.ClassId = 0;
                news.ReadCount = 0;
                home.DbInfo.AddToNews(news);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "添加成功");
            }
            return RedirectToAction("NewList");
            //return View(home.Page<News>(home.News, 0));

        }
        [Authorize]
        public ActionResult NewEdit(int page, int id)
        {
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.News.Where(x => x.Id == id).FirstOrDefault());
        }
        [HttpPost]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult NewEdit(int page, News news)
        {
            if (ModelState.IsValid)
            {
                //news.CreatTime = DateTime.Now;
                home.DbInfo.News.Attach(news);
                home.DbInfo.ObjectStateManager.ChangeObjectState(news, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            //return View("NewList", home.Page<News>(home.News, page));
            return RedirectToAction("NewList", new { page = page });
        }
        [Authorize]
        public ActionResult NewList(int page = 0)
        {
            ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Page<News>(home.News, page));

            //if (Request.IsAjaxRequest())
            //{
            //    return PartialView("NewList", home.Page<News>(home.News, page));
            //}
            //else
            //{
            //    return View(home.Page<News>(home.News, page));
            //}
        }
        [Authorize]
        public ActionResult NewDelete(int page, int id)
        {
            News n = home.News.Where(x => x.Id == id).SingleOrDefault();
            if (n != null)
            {
                home.DbInfo.DeleteObject(n);
                home.DbInfo.SaveChanges();
            }
            return RedirectToAction("NewList", new { page = page });
        }
        #endregion

        #region //添加案例
        [Authorize]
        public ActionResult ListProduct(int page = 0)
        {
            ViewData["pageCount"] = home.Products.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Page<Product>(home.Products, page));
        }
        [Authorize]
        public ActionResult AddProduct()
        {
            return View(new Product());
        }
        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddProduct(Product product,HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    product.ProductPic = FileUpload.UploadFile(file);
                }
                else
                {
                    product.ProductPic = "";
                }

                product.GuidId = Guid.NewGuid().ToString();
                product.CreatDateTime = DateTime.Now;
                product.ClassId = 0;
                product.UserId = 0;
                product.ReadCount = 0;
                product.CompanyId = 0;

                home.DbInfo.AddToProduct(product);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "添加成功");
            }
            return RedirectToAction("ListProduct");
        }
        [Authorize]
        public ActionResult EditProduct(int page, int id)
        {
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Products.Where(x => x.Id == id).FirstOrDefault());

        }

        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditProduct(int page, Product product,HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {

                if (file != null)
                {
                    if (product.ProductPic != null && product.ProductPic != "")
                    {
                        FileUpload.DeleteFile(product.ProductPic);
                    }
                    product.ProductPic = FileUpload.UploadFile(file);
                }
                else
                {
                    product.ProductPic = "";
                }
                product.CreatDateTime = DateTime.Now;
                home.DbInfo.Product.Attach(product);
                home.DbInfo.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return RedirectToAction("ListProduct", new { page = page });

        }
        [Authorize]
        public ActionResult DeleteProduct(int page, int id)
        {
            Product n = home.Products.Where(x => x.Id == id).SingleOrDefault();
            if (n != null)
            {
                if (n.ProductPic != null && n.ProductPic != "")
                {
                    FileUpload.DeleteFile(n.ProductPic);
                }
                home.DbInfo.DeleteObject(n);
                home.DbInfo.SaveChanges();
            }
            return RedirectToAction("ListProduct", new { page = page });
        }
        #endregion

        #region //添加招聘信息
        [Authorize]
        public ActionResult AddJob()
        {
            return View(new Job());
        }
        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddJob(Job job)
        {
            if (ModelState.IsValid)
            {
                job.CreatDateTime = DateTime.Now;
                job.ReadCount = 0;
                home.DbInfo.AddToJob(job);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "添加成功");
            }
            return RedirectToAction("ListJob");

        }
        [Authorize]
        public ActionResult EditJob(int page, int id)
        {
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Jobs.Where(x => x.Id == id).FirstOrDefault());

        }

        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditJob(int page, Job job)
        {
            if (ModelState.IsValid)
            {
                job.CreatDateTime = DateTime.Now;
                job.ReadCount = job.ReadCount;
                home.DbInfo.Job.Attach(job);
                home.DbInfo.ObjectStateManager.ChangeObjectState(job, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return RedirectToAction("ListJob", new { page = page });

        }
        [Authorize]
        public ActionResult ListJob(int page = 0)
        {
            ViewData["pageCount"] = home.Jobs.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Page<Job>(home.Jobs, page));

        }
        [Authorize]
        public ActionResult DeleteJob(int page, int id)
        {
            Job n = home.Jobs.Where(x => x.Id == id).SingleOrDefault();
            if (n != null)
            {
                home.DbInfo.DeleteObject(n);
                home.DbInfo.SaveChanges();
            }
            return RedirectToAction("ListJob", new { page = page });

        }
        #endregion

        #region //添加资料下载
        [Authorize]
        public ActionResult AddDown()
        {
            return View(new Down());
        }
        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddDown(Down down,HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    down.SoftUrl = FileUpload.UploadFile(file);
                }
                else
                {
                    down.SoftUrl = "";
                }
                down.CreatDateTime = DateTime.Now;
                down.ClassId = 0;
                down.ReadCount = 0;
                down.SoftSize = "";

                home.DbInfo.AddToDown(down);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "添加成功");
            }
            return RedirectToAction("ListDown");
        }
        [Authorize]
        public ActionResult EditDown(int page, int id)
        {
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Downloads.Where(x => x.Id == id).FirstOrDefault());

        }

        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditDown(int page, Down down,HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    if (down.SoftUrl != null && down.SoftUrl != "")
                    {
                        FileUpload.DeleteFile(down.SoftUrl);
                    }
                    down.SoftUrl = FileUpload.UploadFile(file);
                }
                else
                {
                    down.SoftUrl = "";
                }

                down.CreatDateTime = DateTime.Now;
                down.ReadCount = down.ReadCount;
                home.DbInfo.Down.Attach(down);
                home.DbInfo.ObjectStateManager.ChangeObjectState(down, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return RedirectToAction("ListDown", new { page = page });

        }
        [Authorize]
        public ActionResult ListDown(int page = 0)
        {
            ViewData["pageCount"] = home.Downloads.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Page<Down>(home.Downloads, page));

        }
        [Authorize]
        public ActionResult DeleteDown(int page, int id)
        {
            Down n = home.Downloads.Where(x => x.Id == id).SingleOrDefault();
            if (n != null)
            {
                if (n.SoftUrl != null && n.SoftUrl != "")
                {
                    FileUpload.DeleteFile(n.SoftUrl);
                }

                home.DbInfo.DeleteObject(n);
                home.DbInfo.SaveChanges();
            }
            return RedirectToAction("ListDown", new { page = page });

        }

        #endregion

        #region//查看及回复留言
        [Authorize]
        public ActionResult ListMsg(int page)
        {
            ViewData["pageCount"] = home.Msg.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Page<Message>(home.Msg, page));
        }
        [Authorize]
        public ActionResult DetailMsg(int page, int id)
        {
            ViewData["pageIndex"] = page;
            return View(home.Msg.Where(x => x.Id == id).FirstOrDefault());

        }
        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditMsg(int page, Message msg)
        {
            if (ModelState.IsValid)
            {
                msg.ReplyTime = DateTime.Now;
                home.DbInfo.Message.Attach(msg);
                home.DbInfo.ObjectStateManager.ChangeObjectState(msg, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            //ViewData["pageCount"] = home.News.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return RedirectToAction("ListMsg", new { page = page });

        }
        [Authorize]
        public ActionResult DeleteMsg(int page, int id)
        {
            Message n = home.Msg.Where(x => x.Id == id).SingleOrDefault();
            if (n != null)
            {
                home.DbInfo.DeleteObject(n);
                home.DbInfo.SaveChanges();
            }
            return RedirectToAction("ListMsg", new { page = page });

        }
        #endregion

        #region//编辑网站配置信息
        [Authorize]
        public ActionResult ListWebConfig()
        {
            return View(home.WebConfig);

        }
        [Authorize]
        public ActionResult EditWebConfig(int id)
        {
            return View(home.WebConfig.Where(x => x.Id == id).SingleOrDefault());
        }
        [Authorize]
        [HttpPost]
        public ActionResult EditWebConfig(WebConfig webconfig)
        {

            if (ModelState.IsValid)
            {
                //这里添加一些修改的信息

                home.DbInfo.WebConfig.Attach(webconfig);
                home.DbInfo.ObjectStateManager.ChangeObjectState(webconfig, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            return RedirectToAction("ListWebConfig");

        }
        //编辑系统信息
        [Authorize]
        public ActionResult ListSysConfig()
        {
            return View(home.SysInfo);
        }

        [Authorize]
        public ActionResult EditSysConfig(int  id)
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView(home.SysInfo.Where(x => x.Id == id).SingleOrDefault());
            }
            else
            {
                return View(home.SysInfo.Where(x => x.Id == id).SingleOrDefault());
            }
        }

        [HttpPost]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult EditSysConfig(SysConfig config)
        {
            if (ModelState.IsValid)
            {
                //这里添加一些修改的信息

                home.DbInfo.SysConfig.Attach(config);
                home.DbInfo.ObjectStateManager.ChangeObjectState(config, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            if (Request.IsAjaxRequest())
            {
                return PartialView("ListSysConfig");
            }
            else
            {
                return RedirectToAction("ListSysConfig");
            }
        }
        #endregion

        #region //用户名管理

        [Authorize]
        public ActionResult ListUsers(int page = 0)
        {
            ViewData["pageCount"] = home.Admins.Count / home.PageSize;
            ViewData["pageIndex"] = page;
            return View(home.Page<Admin>(home.Admins, page));
        }
        [Authorize]
        public ActionResult AddUser()
        {
            return View(new Admin());
        }
        [Authorize]
        [HttpPost]
        public ActionResult AddUser(Admin admin)
        {
            if (ModelState.IsValid)
            {
                admin.RouleId = 0;
                admin.LoginCount = 0;
                admin.CreatTime = DateTime.Now;
                admin.LastLoginTime = DateTime.Now;
                admin.LastLoginIP = Request.UserHostAddress;
                home.DbInfo.AddToAdmin(admin);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "添加成功");
            }
            return RedirectToAction("ListUsers");
        }
        
        [Authorize]
        public ActionResult EditUser(int page, int id)
        {
            ViewData["pageIndex"] = page;
            return View(home.Admins.Where(x => x.Id == id).FirstOrDefault());

        }

        [Authorize]
        [HttpPost]
        public ActionResult EditUser(int page, Admin admin)
        {
            if (ModelState.IsValid)
            {
                home.DbInfo.Admin.Attach(admin);
                home.DbInfo.ObjectStateManager.ChangeObjectState(admin, System.Data.EntityState.Modified);
                home.DbInfo.SaveChanges();
                home.Alert(Response, "修改成功");
            }
            ViewData["pageIndex"] = page;
            return RedirectToAction("ListUsers", new { page = page });

        }
        [Authorize]
        public ActionResult DeleteUser(int page, int id)
        {
            Admin n = home.Admins.Where(x => x.Id == id).SingleOrDefault();
            if (n != null)
            {
                home.DbInfo.DeleteObject(n);
                home.DbInfo.SaveChanges();
            }
            return RedirectToAction("ListUsers", new { page = page });
        }

        #endregion
        [HttpPost]
        public ActionResult UploadImage()
        {
            string savePath = "/Content/Images/";
            string saveUrl = "/Content/Images/";
            string fileTypes = "gif,jpg,jpeg,png,bmp";
            int maxSize = 1000000;

            Hashtable hash = new Hashtable();

            HttpPostedFileBase file = Request.Files["imgFile"];
            if (file == null)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "请选择文件";
                return Json(hash);
            }

            string dirPath = Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传目录不存在";
                return Json(hash);
            }

            string fileName = file.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

            if (file.InputStream == null || file.InputStream.Length > maxSize)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传文件大小超过限制";
                return Json(hash);
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传文件扩展名是不允许的扩展名";
                return Json(hash);
            }

            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            string filePath = dirPath + newFileName;
            file.SaveAs(filePath);
            string fileUrl = saveUrl + newFileName;

            hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;

            return Json(hash, "text/html;charset=UTF-8"); ;
        }
    }
}
